package creator;

import com.appleyk.core.model.LicenseCreatorParam;
import com.appleyk.core.model.LicenseExtraParam;
import com.appleyk.core.service.AServerInfos;
import com.appleyk.core.utils.CommonUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import creator.config.LicenseCreatorProperties;
import creator.service.LicenseCreatorService;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.io.File;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.TimeZone;

/**
 * @Author: WangYao
 * @description:
 * @date: 2024-05-08 10:36
 */
public class Create {

    private static final String key = "mySecretKey123456";
    private LicenseCreatorService creatorService = new LicenseCreatorService();


    private LicenseCreatorProperties properties = new LicenseCreatorProperties();

    public void Create(String key,String IssuedTime,String ExpiryTime) throws Exception {

        // 解密
        String decryptedJson = decrypt(key);
        // 反序列化为对象
        ObjectMapper mapper = new ObjectMapper();
        LicenseExtraParam licenseParam = null;
        licenseParam = mapper.readValue(decryptedJson, LicenseExtraParam.class);
        // 设置需要校验那些硬件
        licenseParam.setCpuCheck(true);
        licenseParam.setMacCheck(true);
        licenseParam.setIpCheck(true);
        licenseParam.setBoardCheck(true);

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        dateFormat.setTimeZone(TimeZone.getTimeZone("GMT+8"));
        // 如果没有人为的指定lic要生成的位置，则程序自动处理
        LicenseCreatorParam param = new LicenseCreatorParam();
        param.setSubject("landi");
        param.setPrivateAlias("privateKeys");
        param.setKeyPass("123456a");
        param.setStorePass("123456a");
        param.setPrivateKeysStorePath("/privateKeys.store");
        // param.setIssuedTime(dateFormat.parse("2024-03-01 08:30:00"));
        // param.setExpiryTime(dateFormat.parse("2024-05-09 14:38:00"));
        param.setIssuedTime(dateFormat.parse(IssuedTime));
        param.setExpiryTime(dateFormat.parse(ExpiryTime));
        param.setDescription("系统软件许可证书");

        // 获取当前机器证书
        // LicenseExtraParam serverInfos = AServerInfos.getServer("").getServerInfos();
        LicenseExtraParam serverInfos = licenseParam;
        param.setLicenseCheck(serverInfos);
        if (CommonUtils.isEmpty(param.getLicensePath())) {
            // 设置格式
            SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
            String tempPath = properties.getTempPath();
            if (tempPath == null || "".equals(tempPath)) {
                // 如果默认临时文件等于空的话，就获取当前服务执行的路径
                tempPath = AServerInfos.getServerTempPath();
            }
            // 根据时间戳，命名lic文件
            String licDir = tempPath + "/lic-files/" + format.format(System.currentTimeMillis());
            File file = new File(licDir);
            if (!file.exists()) {
                if (!file.mkdirs()) {
                    throw new RuntimeException("创建目录" + licDir + ",失败，请检查是是否有创建目录的权限或者手动进行创建！");
                }
            }
            /**统一下路径分隔符*/
            param.setLicensePath(licDir.replace("\\", "/") + "/license.lic");
            creatorService.generateLicense(param);
        }
    }

    public static String decrypt(String encryptedJson) throws Exception {
        byte[] keyBytes = key.getBytes();
        MessageDigest sha = MessageDigest.getInstance("SHA-256");
        keyBytes = sha.digest(keyBytes);
        keyBytes = java.util.Arrays.copyOf(keyBytes, 16);
        SecretKeySpec secretKey = new SecretKeySpec(keyBytes, "AES");

        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        byte[] encryptedBytes = Base64.getDecoder().decode(encryptedJson);
        byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
        return new String(decryptedBytes);
    }
}
